/*
 * @Author: cql-cql-cql
 * @Date:   2017-04-17 08:28:40
 * @Last Modified by:   cql-cql-cql
 * @Last Modified time: 2017-05-08 22:30:06
 */
var formidable = require('formidable')
var db = require('../models/my_db')
var md5 = require('../models/md5')
var path = require("path")
var fs = require("fs")
var Mock = require('mockjs')
var axios = require('axios')
var ObjectID = require('mongodb').ObjectID

exports.doRegister = function (req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        var name = fields.name;
        var checkPass = fields.checkPass;
        var email = fields.email;
        // var pass = fields.pass;
        checkPass = md5(checkPass);

        db.findDocuments("users", {"name": name}, function (err, data) {
                if (err) {
                    res.send("-3")
                } else if (data.length > 0) {
                    res.send("-1")
                } else {
                    db.insertDocuments("users", {
                            "name": name,
                            "checkPass": checkPass,
                            "email": email,
                            // "pass": pass,
                            "avator": "default.jpg",
                            'detail': [],
                        },
                        function (err, data) {
                            // console.log(err);
                            if (err) {
                                res.send("-3")
                            } else {
                                req.session.login = 1;
                                req.session.name = name;
                                req.session.email = email;
                                req.session.checkPass = checkPass;
                                // req.session.pass = pass;
                                req.session.avator = 'default.jpg';
                                res.send('1')
                            }
                        })
                }
            }
        )
    });
}
exports.doLogin = function (req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        var name = fields.name;
        var password = md5(fields.checkPass);
        db.findDocuments("users", {"name": name}, function (err, data) {
                if (err) {
                    res.send("-3");
                    return
                }
                if (data.length == 0) {
                    res.send("-4");
                    console.log(222);
                    return
                }
                if (data[0].checkPass == password) {
                    req.session.login = 1;
                    req.session.name = name;
                    req.session.avator = data[0].avator;
                    res.send("1");
                } else {
                    res.send("-1");
                }
            }
        )
    });
}
exports.resetpass = function (req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        var name = fields.name;
        var save = fields.save;
        var checkPass = md5(fields.checkPass);
        db.findDocuments("users", {"name": name}, function (err, data) {
                console.log('one');
                if (err) {
                    res.send("-3");
                    return
                }
                if (data.length == 0) {
                    res.send("-4");
                    console.log(222);
                    return
                }
                if (data[0].save == save) {
                    console.log('true');
                    db.updateDocuments("users", {"name": name}, {
                            "checkPass": checkPass,
                        },
                        function (err, data) {
                            // console.log(err);
                            if (err) {
                                res.send("-3")
                            } else {
                                res.send('1')
                            }
                        })
                } else {
                    res.send("-1");
                }
            }
        )
    });
}


exports.poepleInfo = function (req, res, next) {
    if (req.session.login == "1") {
        var name = req.session.name;
        var avator = req.session.avator
        db.findDocuments('users', {'name': name}, function (err, result) {
            if (err) {
                console.log(err);
            }
            // console.log(result[0]);
            // console.log(result[0]);
            // console.log(name);
            // console.log(result[0]);
            res.send({
                'login': 1,
                'name': name,
                'realName': result[0].realName,
                'mobile': result[0].mobile,
                'address': result[0].address,
                'avator': avator,
                'email': result[0].email,
                'save': result[0].save,
                'detail': result[0].detail,
            });
        })
    } else {
        res.json({"result": 0});
    }
}
exports.avator = function (req, res, next) {
    var form = new formidable.IncomingForm();
    form.uploadDir = path.normalize(__dirname + "/../avator/");
    form.parse(req, function (err, fields, files, next) {
        var oldpath = files.img.path;
        var newpath = path.normalize(__dirname + '/../avator/' + req.session.name + '.jpg')

        console.log('上传')
        fs.rename(oldpath, newpath, function (err) {
            if (err) {
                console.log(err);
                res.send("失败");
                return;
            }
            console.log('修改名字')
            req.session.avator = req.session.name + ".jpg";
            db.updateDocuments("users", {"username": req.session.username}, {
                "avator": req.session.avator
            }, function (err, results) {
                console.log('更新成功')

                res.json({result: 'OK'})
            });

        })
    });
}
exports.logout = function (req, res, next) {
    req.session.login = '0';
    res.send('1')
}

//捐赠
exports.my = function (req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files, next) {
        // console.log(fields)
        var name = req.session.name;
        // console.log(name);
        db.updateDocuments("users", {"name": name}, {
            'name': fields.name,
            'realName': fields.realName,
            'mobile': fields.mobile,
            'email': fields.email,
            'address': fields.address,
            'save': fields.save,
        }, function (err, results) {
            // console.log(results);
            res.send('1')
        });

    });
}


exports.message = function (req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files, next) {
        // console.log(fields)
        var name = req.session.name;
        // console.log(name);
        db.updateDocuments_push("users", {"name": name}, {
            'detail': {
                goodsName: fields.goodsName,
                messages: fields.messages,
                selected: fields.selected,
                date: Date.now()
            }
        }, function (err, results) {
            // console.log(results);
            res.send('1')
        });

    });
}

//public页面
exports.donations = function (req, res, next) {
    var param = req.params['par'];
    var page = parseInt(req.query.page);
    var most = req.query.most;
    var year = parseInt(req.query.year);
    // console.log(param+'--'+page);
    // console.log(most+'--'+most);
    // console.log(year+'--'+year);
    if (!year) {
        db.findDocuments(param, {}, {sort: {"date": -1}, "pageamount": 15, "page": page}, function (err, result) {
            if (err)
                console.log(err);
            res.json(result);
        })
    } else {
        db.findDocuments(param, {'date': new RegExp(year)}, {
            sort: {"date": -1},
            "pageamount": 15,
            "page": page
        }, function (err, result) {
            if (err)
                console.log(err);
            res.json(result);
        })
    }
}
exports.count = function (req, res, next) {
    var param = req.params['par'];
    var year = parseInt(req.query.year);
    console.log(req.query.year);
    // console.log(param);
    if (year) {
        db.findAll(param, {'date': new RegExp(year)}, function (err, result) {
            if (err)
                console.log(err);
            res.json(result)
        })
    } else {
        db.findAll(param, {}, function (err, result) {
            if (err)
                console.log(err);
            res.json(result)
        })
    }
}
exports.service = function (req, res, next) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files, next) {
        axios.post('http://www.tuling123.com/openapi/api', {
            'key': '695409b3cda342639aac8ab1e337db34',
            'info': fields.info,
        }).then(function (data) {
            // console.log(data);
            res.json(data.data)
        }).catch(function (err) {
        })
    });

}
exports.rank = function (req, res, next) {
    db.findDocuments("comment", {}, {sort: {"like": -1}}, function (err, result) {
        if (err) console.log(err);
        res.json(result)
    })
}


//发现页面开始
exports.list = function (req, res, next) {
    //console.log(req.query.size + "  " + req.query.page)
    db.findDocuments("comment", {}, {
        sort: {"date": -1},
        "pageamount": parseInt(req.body.size),
        "page": req.body.page
    }, function (err, result) {
        if (err) console.log(err);
        res.json(result)
    })
}

exports.melist = function (req, res, next) {
    db.findDocuments("comment", {'name': req.body.name}, {sort: {"date": -1}}, function (err, result) {
        if (err) console.log(err);
        res.json(result)
    })
}


exports.addComment = function (req, res, next) {
    // console.log(req.body)
    db.insertDocuments("comment", req.body,
        function (err, data) {
            res.send("addComment")
        })
}

exports.addReply = function (req, res, next) {
    db.updateDocuments_push("comment", {"_id": ObjectID(req.body._id)}, {
        'discuss': {name: req.body.name, data: req.body.data}
    }, function (err, results) {
        db.findDocuments("comment", {"_id": ObjectID(req.body._id)}, function (err, result) {
            if (err) console.log(err);
            res.json(result)
        })
    });
}
exports.changeLike = function (req, res, next) {
    //console.log("value")
    db.findDocuments("comment", {
        "_id": ObjectID(req.body._id)
    }, function (err, result) {
        if (req.body.bool) {
            db.updateDocuments("comment", {"_id": ObjectID(req.body._id)}, {
                'like': result[0].like + 1
            }, function (err, results) {
                res.json(results)
            });
        } else {
            db.updateDocuments("comment", {"_id": ObjectID(req.body._id)}, {
                'like': result[0].like - 1
            }, function (err, results) {
                res.json(results)
            });
        }

        //res.send("findDocuments")
    })
}
//发现页面结束






